package com.cupcorn.balapkarung.entity;

import org.andengine.engine.camera.ZoomCamera;
import org.andengine.engine.handler.IUpdateHandler;

import com.cupcorn.lib.game.GameEngine;

public class Camera
{
	Map[]		map;
	MC			mc;
	ZoomCamera	camera;
	int			firstMap, lastMap;
	
	public Camera(final ZoomCamera camera, final MC mc, Map... map)
	{
		this.map = map;
		this.camera = camera;
		this.mc = mc;
		firstMap = 0;
		lastMap = map.length - 1;
		camera.setBounds(map[firstMap].recMap.getX(), 0, map[lastMap].recMap.getX() + map[lastMap].recMap.getWidth(), map[0].recMap.getHeight());
		camera.setBoundsEnabled(true);
		camera.setZoomFactor(GameEngine.CAMERA_HEIGHT / 480);
		camera.registerUpdateHandler(new IUpdateHandler()
		{
			public void reset()
			{}
			
			public void onUpdate(float pSecondsElapsed)
			{
				camera.setCenter(mc.mc.getX() + mc.mc.getWidth() / 2 + camera.getWidth() / 4, mc.mc.getY() + mc.mc.getHeight() / 2);
			}
		});
	}
	
	public void onUpdate()
	{
		if (map[firstMap].recMap.getX() + map[firstMap].recMap.getWidth() < camera.getXMin())
		{
			map[firstMap].setX((int) map[firstMap].recMap.getWidth() * 2);
			nextFirstMap();
			nextLastMap();
		}
		camera.setBounds(camera.getXMin(), 0, map[lastMap].recMap.getX() + map[lastMap].recMap.getWidth(), map[0].recMap.getHeight());
	}
	
	private void nextFirstMap()
	{
		firstMap += 1;
		if (firstMap == map.length)
		{
			firstMap = 0;
		}
	}
	
	private void nextLastMap()
	{
		lastMap += 1;
		if (lastMap == map.length)
		{
			lastMap = 0;
		}
	}
	
	public void reset()
	{
		firstMap = 0;
		lastMap = map.length - 1;
		for (int i = 0; i < map.length; i++)
		{
			map[i].reset();
		}
		camera.setBounds(map[firstMap].recMap.getX(), 0, map[lastMap].recMap.getX() + map[lastMap].recMap.getWidth(), map[0].recMap.getHeight());
		camera.setCenter(0, 0);
	}
}
